package com.pandora.common.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pandora.framework.constant.Constants;
import com.pandora.framework.util.LogUtils;

/**
 * web请求工具类
 * 
 * @author JingChenglong 2017/12/15 18:41
 *
 */
public class WebUtils {

	/**
	 * 获取本机地址
	 * 
	 * @return
	 */
	public static String getLocalHost() {
		try {
			return InetAddress.getLocalHost().toString();
		} catch (UnknownHostException e) {
			LogUtils.logError(CommonUtils.getTraceInfo() + e.getMessage());
		}
		return "";
	}

	/**
	 * 获取请求体IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {

		if (request == null) {
			return "";
		}

		String ip = request.getHeader("x-forwarded-for");

		if (StringUtils.isInvalid(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			if (StringUtils.isInvalid(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
				if (StringUtils.isInvalid(ip)) {
					ip = request.getRemoteAddr();
				}
			}
		} else {
			String[] ips = ip.split(",");
			for (String tempIp : ips) {
				if (StringUtils.isNotEmpty(tempIp) && !Constants.UNKNOWN.equals(tempIp)) {
					ip = tempIp;
					break;
				}
			}
		}

		return StringUtils.nullToStrTrim(ip);
	}

	/**
	 * 获取请求体中的指定内容
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getHeader(HttpServletRequest request, String name) {

		return StringUtils.nullToStrTrim(request.getHeader(name));
	}

	/**
	 * 获取请求体中指定内容并解码
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getHeaderDecode(HttpServletRequest request, String name) {

		return StringUtils.decode(request.getHeader(name));
	}

	/**
	 * 根据IP地址获取IP归属地
	 * 
	 * @param ip
	 * @return
	 */
	public static String getAddressByIp(String ip) {
		// TODO 根据IP地址获取IP归属地
		if (StringUtils.isInvalid(ip)) {
			return "";
		}

		return "";
	}

	public static void flushBuffer(HttpServletResponse response) {

		try {
			response.flushBuffer();
		} catch (IOException e) {
			LogUtils.logError(CommonUtils.getTraceInfo() + e.getMessage());
		}
	}
}